﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Threading;

namespace iPdf
{
    public enum ItemStatus
    {
        Idle = 0,
        Processing = 1,
        Done = 2,
        Error = 3
    }

    public class ProcessItemEventArgs : EventArgs
    {
        public int Index;
        public ItemStatus Status;
        public ActionReport Report;
        public TataException Exception;

        public ProcessItemEventArgs(int index)
        {
            Index = index;
        }

        public ProcessItemEventArgs(int index, ItemStatus status, TataException exception)
        {
            Index = index;
            Status = status;
            Exception = exception;
        }

        public ProcessItemEventArgs(ActionReport report)
        {
            Report = report;
        }
    }

    public abstract class VirtualActor
    {
        #region Fields
        public static event EventHandler<ProcessItemEventArgs> ItemStarted;
        public static event EventHandler<ProcessItemEventArgs> ItemFinished;
        public static event EventHandler<ProcessItemEventArgs> AllItemsFinished;

        protected BackgroundWorker worker;

        #endregion

        #region Ctor
        protected VirtualActor()
        {
            worker = new BackgroundWorker();
        }
        #endregion

        #region Methods

        protected void NotPrepared(int itemCount)
        {
            if (AllItemsFinished != null)
            {
                ActionReport report = new ActionReport();
                report.ErrorItemsCount = 0;
                report.DoneItemsCount = 0;
                report.UndoneItemsCount = itemCount;
                AllItemsFinished(this, new ProcessItemEventArgs(report));
            }
        }

        protected void StartItem(int curItemIndex)
        {
            if (ItemStarted != null)
            {
                ItemStarted(this, new ProcessItemEventArgs(curItemIndex));
            }
        }

        protected void FinishItem(int curItemIndex, ItemStatus curItemStatus, TataException exception)
        {
            if (ItemFinished != null)
            {
                ItemFinished(this, new ProcessItemEventArgs(curItemIndex, curItemStatus, exception));
            }
        }

        protected void FinishAllItems(ActionReport report)
        {
            if (AllItemsFinished != null)
            {
                AllItemsFinished(this, new ProcessItemEventArgs(report));
            }
        }

        protected virtual void Work()
        {
        }

        protected virtual void Prepare()
        {
        }

        protected virtual void Finish()
        {
            Helper.CollectGarbage();
        }

        #endregion
    }
}
